# Create map
map <- leaflet() %>%
addTiles(group = "OpenStreetMap") %>%
setView(lng = -157.8583, lat = 20.9078, zoom = 7)
raw_polygons <- st_read("raw_data/Ahupuaa.geojson")
#> Reading layer `Ahupuaa' from data source
#> `/Users/kishi/Documents/Dev/ahupuaa-dashboard/raw_data/Ahupuaa.geojson'
#> using driver `GeoJSON'
#> Simple feature collection with 727 features and 9 fields
#> Geometry type: POLYGON
#> Dimension: XY
#> Bounding box: xmin: -160.247 ymin: 18.91069 xmax: -154.8066 ymax: 22.23529
#> Geodetic CRS: WGS 84
# Function to create adjacency-based coloring
color_adjacent_polygons <- function(polygons_sf, num_colors = 4) {
# Create adjacency matrix
adjacency <- st_touches(polygons_sf, sparse = FALSE)
# Initialize colors
n_polygons <- nrow(polygons_sf)
colors <- rep(NA, n_polygons)
color_palette <- RColorBrewer::brewer.pal(num_colors, "GnBu")
# Simple greedy coloring algorithm
for (i in 1:n_polygons) {
# Get neighbors
neighbors <- which(adjacency[i, ])
# Get colors already used by neighbors
used_colors <- unique(colors[neighbors])
used_colors <- used_colors[!is.na(used_colors)]
# Find first available color
available_colors <- setdiff(1:num_colors, used_colors)
if (length(available_colors) > 0) {
colors[i] <- available_colors[1]
} else {
# If no color available, use first color (fallback)
colors[i] <- 1
}
}
# Add colors to the sf object
polygons_sf$color_id <- colors
polygons_sf$fill_color <- color_palette[colors]
return(polygons_sf)
}
# Apply coloring
colored_ahupuaa <- color_adjacent_polygons(raw_polygons, num_colors = 5)
# Add ahupuaa polygons
map <- map %>%
addPolygons(
data = colored_ahupuaa,
label = ~ahupuaa,
group = "Ahupuaa Fill",
fillColor = ~fill_color,
fillOpacity = 0.5,
color = ~fill_color,
stroke = TRUE,
weight = 2,
)
map